package com.longxiao.validator.parser;


import com.longxiao.validator.ValidResult;
import com.longxiao.validator.anno.ValiNumber;

import java.lang.annotation.Annotation;

/**
 * Created by houhongwei on 2017/5/12.
 */
public class ValiNumberParser extends Parser {

    private static final double SKIP = -999;

    @Override
    protected ValidResult doValid(Object value, Annotation annotation) {
        ValiNumber anno = (ValiNumber) annotation;
        Double doubleValue = getDoubleValue(value);
        double min = anno.min();
        if (min != SKIP) {
            if (doubleValue < min) {
                return ValidResult.createFail(anno.err());
            }
        }
        double max = anno.max();
        if (max != SKIP) {
            if (doubleValue > max) {
                return ValidResult.createFail(anno.err());
            }
        }

        // 验证参考值
        boolean bool = validRef(doubleValue, anno);
        if (bool == Boolean.FALSE) {
            return ValidResult.createFail(anno.err());
        }
        return ValidResult.createSucc();
    }

    @Override
    public Class getAnno() {
        return ValiNumber.class;
    }

    @Override
    protected boolean isRequired(Annotation annotation) {
        return ((ValiNumber) annotation).required();
    }

    @Override
    protected String getErr(Annotation annotation) {
        return ((ValiNumber) annotation).err();
    }

    private boolean validRef(double doubleValue, ValiNumber anno) {
        // 验证参考值
        double[] arr = anno.ref();
        double tmp = arr[0];
        if (tmp != SKIP) {// -999 默认值，不做验证  != -999 必须要验证
            boolean succ = Boolean.FALSE;
            for (double d : arr) {
                if (d == doubleValue) {
                    succ = Boolean.TRUE;
                    break;
                }
            }
            if (succ == Boolean.FALSE) {
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }


    private Double getDoubleValue(Object value) {

        Double d = null;
        if (value.getClass().isArray()) {
            d = (((Number[]) value)[0]).doubleValue();
        }
        if (value instanceof Number) {
            d = ((Number) value).doubleValue();
        }
        return d;
    }
}
